package tema10.controller;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class BasicUtilitiesServlet extends HttpServlet {

    protected final String successForm = "/WEB-INF/view/successForm.jsp";
    protected final String errorForm = "/WEB-INF/view/errorForm.jsp";
    protected final String displayForm = "/WEB-INF/view/displayForm.jsp";
    protected String persistenceMechanism = null;

    protected abstract void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException;

    protected void gotoNamedResource(String address, HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        RequestDispatcher dispatcher = getServletContext().getNamedDispatcher(address);
        dispatcher.forward(request, response);
    }

    protected void gotoURL(String address, HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }

    @Override
    public void init() {
        ServletConfig config = getServletConfig();
        ServletContext context = config.getServletContext();
        //Para mencionar (como comprobacion) el tipo de persistencia que usamos
        persistenceMechanism = context.getInitParameter("persistenceMechanism");
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        persistenceMechanism = (String) getServletContext().getAttribute("persistenceMechanism");
        processRequest(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        persistenceMechanism = (String) getServletContext().getAttribute("persistenceMechanism");
        processRequest(request, response);
    }
}
